# -*- coding:utf-8 -*-
import json
import os
import subprocess
import re
import hashlib
import time
import threading

server_path = '/opt/ros/server/serverip.cfg'
id_path = '/opt/ros/machineinfo/robot_id'

if os.path.isfile('/mooe/machineinfo/robot_id'):
    id_path = '/mooe/machineinfo/robot_id'

if os.path.isfile('/mooe/server/serverip.cfg'):
    server_path = '/mooe/server/serverip.cfg'

def serverIP(path):
    fs = open(path, 'r')
    data = fs.read().strip()
    fs.close()
    ip = data.split('=')[1]
    return ip
def get_robot_uuid(path):
    fs = open(path, 'r')
    id = fs.read().strip()
    fs.close()
    return id
def getVersion(msg):
    import json
    info_data = msg.data.split(":")
    version_data = info_data[1:len(msg.data)]
    str_data = ":".join(version_data)
    json_data = json.loads(str_data)
    mapverion = str(json_data['mapverion'])
    controlverion = str(json_data['controlverion'])
    robotid = str(json_data['robotid'])
    robotseries = str(json_data['robotseries'])
    robotverion = str(json_data['robotverion'].replace("\n", ''))
    send_version = {"mapverion": mapverion, "controlverion": controlverion, "robotid": robotid,
                    "robotseries": robotseries, "robotverion": robotverion}
    return send_version
#读取ifconfig信息
def read_ifconfig():
    p = subprocess.Popen('ifconfig', stdout=subprocess.PIPE, shell=True)
    return p.communicate()[0]
#返回网卡及ip信息：网卡、IP址、MAC地址
def get_ipinfo(data):
    data = (i for i in data.split('\n\n') if i and not i.startswith('lo'))
    ip_info = []
    ifname = re.compile(r'(eth[\d:]*|wlan[\d:]*|enp1s[\d:]*)')
    ipaddr = re.compile(r'(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})){3}')
    macaddr = re.compile(r'[A-F0-9a-f:]{17}')
    for i in data:
        x = {}
        if ifname.match(i):
            device = ifname.match(i).group()
            x['Adapter'] = device
        if macaddr.search(i):
            mac = macaddr.search(i).group()
            x['MAC'] = mac
        if ipaddr.search(i):
            ip = ipaddr.search(i).group()
            x['IP'] = ip
        else:
            x['IP'] = None
	if 'Adapter' in x and (x['Adapter'] == 'enp1s0' or x['Adapter'] == 'wlan0'):
            ip_info.append(x)
        else:
            continue
        if x['Adapter'][0:3] == "eth" or x['Adapter'] == "enp1s0":
            ip_info.append(x)
        elif x['Adapter'][0:4] == "wlan":
            if len(ip_info) < 2:
                ip_info.insert(0,x)
            else:
                if ip_info[0]['Adapter'][0:3] == "eth":
                    ip_info.insert(0,x)
                else:
                    Adapter1=x['Adapter'][4]
                    Adapter2=ip_info[0]['Adapter'][4]
                    if int(Adapter1)<int(Adapter2):
                        ip_info.insert(0,x)
                    else:
                        ip_info.insert(1,x)
    return ip_info

adapters='wlan0|wlan1|wlan2|wlan3|wlan4|wlan5|eth0|eth1|enp1s0'

        
def get_robot_id(cmd):
    global adapters
    ipinfo=get_ipinfo(read_ifconfig())
    for item in ipinfo:
        if isinstance(item,str):
            continue
        if item["IP"] == None:
            continue
        elif re.match(adapters,item["Adapter"]):
            if cmd=="IP":
                return item["IP"]
            elif cmd=="MAC":
                return item["MAC"]

#print(get_robot_id("IP"))


server_ip = serverIP(server_path)
robot_id=get_robot_uuid(id_path)

